import ajax from 'uni-ajax' // 引入 uni-ajax 模块
// import Toast from 'vant/lib/toast';
// import Config from '@/utils/Config.js'
import $gl from '../js/global.js'

// 创建请求实例
const uniajax = ajax.create({
	// 默认配置
	baseURL: Config.ProjectAPI,
	header: {
		'Content-Type': 'application/json;charset=UTF-8',
		// 'Content-Type': 'application/x-www-form-urlencoded',
	},
	method: "POST",
	dataType: "json",
	responseType: "text",
	loading: true,
	success: () => {},
	fail: () => {},
	complete: () => {},
})

// 添加请求拦截器
uniajax.interceptors.request.use(
	config => {
 
		config.header.post['Authorization'] = uni.getStorageSync('token');

		if (config.loading) {
			uni.showLoading({
				title: "数据加载中...",
			})
		}

		return config
	},
	error => {

		return Promise.reject(error)
	}
)

// 添加响应拦截器
uniajax.interceptors.response.use(
	response => {


		if (response.config.loading) {
			uni.hideLoading()
		}

		return response.data
	},
	error => {
		
		$gl.toastHide();

		let obj = {};

		if (error.statusCode === 401) {
			$gl.toastFail("登录已失效，请重新登录");

			setTimeout(() => {
				uni.navigateTo({
					url: "/pages/Login"
				});
				uni.removeStorageSync('token');
			}, 2000)

		} else if (error.statusCode === 405) {

			if (typeof error.data == 'object') {
				obj.message = error.data.Message;
			}
			$gl.toastFail(obj.message);

		} else if (error.statusCode === 404) {

			if (typeof error.data == 'string') {
				obj.message = "无法找到资源";
			}
			$gl.toastFail(obj.message);

		} else {
			obj.message = error.message != undefined ? error.message : error.data;
			
			if(!$gl.IsNullOrEmpty(obj.message))
			{
				$gl.toastFail(obj.message);
			}
			else{
				$gl.toastFail();
			}
		}

		return Promise.reject(obj)
	}
)
export default uniajax
